<template>
  <base-modal
    :show.sync="show"
    width="420px"
    class="userules-dialog"
    @closed="onClose"
  >
    <div slot="title">
      <span class="el-dialog__title">{{$t('task.setting.taskTypeSetting.flow.components.taskCardTitle5')}}</span>
    </div>
    <div class="base-modal-content">
      <div class="base-form-list">
        <label>{{$t('task.setting.taskTypeSetting.flow.components.taskCardTitle6')}}
          <el-tooltip
            class="item"
            effect="dark"
            :content="$t('task.setting.taskTypeSetting.flow.components.taskCardTip2')"
            placement="top"
          >
            <span><i class="el-icon-question"></i></span>
          </el-tooltip>
        </label>
        <el-select v-model="form.stateCanEdit" @change="onChangeState" multiple :placeholder="$t('common.placeholder.select')">
          <el-option
            v-for="item in flowStateShow"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </div>
      <div class="base-form-list">
        <label>{{$t('task.setting.taskTypeSetting.flow.components.taskCardTitle7')}}
          <el-tooltip
            class="item"
            effect="dark"
            placement="top"
          >
            <div slot="content">
              <template>
                <div class="form-displaymode-setting-item"><span>●</span> {{$t('task.setting.taskTypeSetting.flow.components.taskCardTitle8')}}</div>
                <div class="form-displaymode-setting-item"><span>●</span> {{$t('task.setting.taskTypeSetting.flow.components.taskCardTitle9')}}</div>
              </template>
            </div>
            <span><i class="el-icon-question"></i></span>
          </el-tooltip>
        </label>
        <el-select v-model="form.flow" clearable :placeholder="$t('task.setting.taskTypeSetting.flow.components.taskCardPlaceholder1')">
          <el-option
            v-for="item in flowRulesShow"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </div>
    </div>
    <div slot="footer" class="dialog-footer">
      <el-button @click="onClose">{{$t('common.base.cancel')}}</el-button>
      <el-button type="primary" @click="onSubmit('form')">{{$t('common.base.makeSure')}}</el-button>
    </div>
  </base-modal>
</template>
<script>
// api
import * as SettingTaskApi from '@src/api/SettingTaskApi';
/* utils*/
import {flowState , flowRules, flowMapState, toFieldArray, flowStateNameEnum, flowBtnNameEnum} from './useRules';
import { isBasicEditionHidePay } from '@shb-lib/version';
import { re } from 'mathjs';
import { GrayFunctionEnum } from 'pub-bbx-global/pageType/dist/grayFunction'
import { getRootWindow } from "@src/util/dom";
import { fieldArrayToObject } from "@src/util/array";
import i18n from "@src/locales";
export default {
  name: 'use-rules-dialog',
  props: {
    taskCard: {
      type: Object,
      default: () => ({})
    },
    taskTypeId:{
      type: String,
    },
    visiable: {
      type: Boolean,
    },
  },
  data() {
    return {
      show: false,
      flowRulesShow: [],
      form: {
        id: '',
        flow:'',
        stateCanEdit: [],
        description: '',
        inputType: 'single',
      },
      flowStateAll: [], // 自定义节点+系统节点的状态
      flowRulesAll: [], // 自定义节点+系统节点的按钮
      flowMapStateAll: {}, // 状态和按钮的映射关系
    };
  },
  computed: {
    flowStateShow() {
      const states = this.flowStateAll
      // 基础版过滤结算字段
      if (this.isBasicEditionHidePay) {
        return states.filter(item => item.value !== 'costed')
      }

      return states
    },
    isBasicEditionHidePay() {
      return isBasicEditionHidePay() 
    },
    // 是否开启了流程节点灰度
    isOpenTaskFlowExtend() {
      const RootWindow = getRootWindow(window);
      return RootWindow?.grayAuth?.[GrayFunctionEnum.TaskFlowExtend] ?? false // 工单流程节点灰度
    },
    flowStateNames() {
      return flowStateNameEnum();
    },
    flowBtnNames() {
      return flowBtnNameEnum();
    },
  },
  watch: {
    visiable(newValue) {
      if(newValue){
        this.form.flow = this.taskCard.notNullFlow ? this.taskCard.notNullFlow : '';
        this.form.stateCanEdit = this.taskCard.stateCanEdit ? this.taskCard.stateCanEdit : [];
        // 开启了流程节点，需要动态获取规则的状态和按钮
        this.getAllNodeInfo()
      }else {
        this.show = newValue;
      }
    },
  },
  methods: {
    // 获取当前工单类型的所有节点和状态：用于设置规则
    async getAllNodeInfo() {
      this.flowStateAll = [];
      this.flowMapStateAll = {};
      this.flowRulesAll = [];

      try {
        if(this.isOpenTaskFlowExtend) {
          const { success, result, message } = await SettingTaskApi.getTaskFlowNodeAddons({taskTypeId: this.taskTypeId});

          if (!success) return this.$message.error(message)

          result?.forEach((item, index) => {
            // 状态
            item.nodeState && this.flowStateAll.push({
              value: item.nodeState,
              label: this.flowStateNames?.[item.nodeState] ?? item.nodeStateName,
            })

            /*按钮*/
            let btns = []
            // 已接单和已完成的时候，不能取buttonInfoList，此时下个节点可能是自定义字段,自定义节点也需要取下一个节点的buttonInfoList
            if(item?.type === 'normal' && result?.[index+1]?.type !== 'normal'){
              btns = [{value: 'finish', label: i18n.t('common.base.finish')}]
              if(this.flowRulesAll?.every(item => item.value !== 'finish')){
                this.flowRulesAll.push(btns[0])
              }
            }else if((['accepted', 'processing'].includes(item.nodeState) && result?.[index+1]?.type === 'normal') || item?.type === 'normal') {
              btns = this.getFlowBtn(result?.[index+1]);
            } else {
              btns = this.getFlowBtn(item);
            }
            // 映射
            this.$set(this.flowMapStateAll, item.nodeState, btns)

          })

        } else {
          this.flowStateAll = flowState;
          this.flowMapStateAll = flowMapState;
          this.flowRulesAll = flowRules;
        }
      } catch (e) {
        console.error('getAllNodeInfo error', e)
      } finally {
        this.handlerFlowRules();
        this.show = true;
      }
    },
    getFlowBtn(item) {
      // 按钮
      return item?.buttonInfoList?.map(item => {
        const btn = {
          label: this.flowBtnNames?.[item.key] ?? item.nodeBtnName,
          value: item.key,
        }
        if(this.flowRulesAll?.every(item => item.value !== btn.value)){
          this.flowRulesAll.push(btn)
        }
        return btn
      })
    },
    // 处理节点按钮显示
    handlerFlowRules() {
      // 回显处理，避免节点删除后，已经选中的值回显显示id
      this.form.stateCanEdit = this.form.stateCanEdit?.filter(id => this.flowStateAll?.findIndex(item => item.value === id) > -1)

      let option = this.getFlowRuleOptions(this.form.stateCanEdit);
      if (this.isBasicEditionHidePay) {
        this.flowRulesShow = option.filter(item => item.value !== 'cost')
      } else {
        this.flowRulesShow = option;
      }
      // 回显处理，避免节点删除后，已经选中的值回显显示id
      if(this.flowRulesShow?.every(item => item.value !== this.form.flow)) this.form.flow = ''

    },
    getFlowRuleOptions(keys) {
      if(Array.isArray(keys)){
        if(keys.length === 0){
          return this.flowRulesAll
        }
        let option = [];
        keys.forEach(item=>{
          let values = this.flowMapStateAll[item] || [];
          option.push(...values)
        });
        option = toFieldArray(fieldArrayToObject(option, 'value'), this.flowRulesAll)

        return option
      } else if(keys){
        return this.flowMapStateAll[keys] || []
      }
      return this.flowRulesAll
    },
    onChangeState(value) {
      let option = this.getFlowRuleOptions(value);
      if (this.isBasicEditionHidePay) {
        this.flowRulesShow = option.filter(item => item.value !== 'cost')
      } else { 
        this.flowRulesShow = option;
      }
      this.form.flow = '';
    },
    onClose() {
      this.$emit('onClose')   
    },
    onSubmit(form) {
      // 新增组件
      this.saveRulesFlow();
    },

    // 创建附加组件
    saveRulesFlow() {
      this.$emit('update', this.form.flow, this.form.stateCanEdit)
    },

    // 修改附加组件
    onUpdateCardReq() {
      const params = {
        description: this.form.description,
        id: this.form.id,
        name: this.form.name,
      };
      SettingTaskApi.onUpdateCard(params)
        .then((res) => {
          const { status, message, data } = res;
          if (status == 0) {
            this.$message.success(this.$t('common.base.tip.editSuccess'));
            location.reload();
          } else {
            this.$message.error(message);
          }
        })
        .catch((error) => {
          console.log(error);
        });
    },

    // 获取附加组件的信息
    getCardInfoReq() {
      SettingTaskApi.getCardInfo({ id: this.form.id })
        .then((res) => {
          const { status, message, data } = res;
          if (status == 0) {
            this.form = data;
          }
        })
        .catch((error) => ({}));
    },
  },
};
</script>
<style lang="scss">
.userules-dialog {
  .base-modal-header {
    display: flex;
    justify-content: space-between;
    .el-dialog__title {
      font-size: 18px;
    }
    .el-tooltip {
      color: #999;
    }
  }
  .base-modal-body {
    padding: 20px;
    .el-form {
      .el-form-item {
        .el-form-item__content {
          width: 280px;
          .el-radio {
            margin-right: 24px;
          }
        }
        .el-tooltip {
          color: #999;
        }
      }
    }
  }
  .base-modal-content{
    .base-form-list{
      margin-bottom: 20px;
      label{
        font-size: 14px;
        color: #666666;
        .el-tooltip{
          color: #999;
        }
      }
      .el-select{
        width: 100%;
      }
    }
  }
}
</style>
